home *** CD-ROM | disk | FTP | other *** search
- Path: news.gate.net!pslfl2-37
- From: bhutto@gate.net (William Hutto)
- Newsgroups: comp.lang.c
- Subject: Re: ** Array problem **
- Date: 20 Jan 1996 23:03:25 GMT
- Organization: CyberGate, Inc.
- Message-ID: <4drsbt$il4@news.gate.net>
- References: <4dqh8k$ov9@neptunus.pi.net>
- NNTP-Posting-Host: pslfl2-37.gate.net
- X-Newsreader: News Xpress Version 1.0 Beta #4
-
- In article <4dqh8k$ov9@neptunus.pi.net>, mv@pi.net spake:
- ;
- ;Hello Bill Wendlig (and everybody else),
- ;
- ;
- ;A couple a days ago you replied to a message from me about some
- ;problems with a piece if code..
- ;You handed me some tips and corrections about a double indexed array that
- ;turned out to be a 3-dimensional one..
- ;
- ;I implemented you corrections but to no good, it made things even worse...
- ;But than again I'm not a an experienced C-programmer..
- ;
- ;But could you please tell me why this code works...
- ;
- ;
- ;--------------------------------------------
- ;
- ;#include <stdio.h>
- ;#include <stdlib.h>
- ;#include <string.h>
- ;#include <malloc.h>
- ;
- ;
- ;char *s;
- ;char a[20][20];
- ;
- ;
- ;
- ;int main (void)
- ;
- ;{
- ; int i=0;
- ;
- ; s=(char *)malloc(18);
- ; strcpy(s,"Blah blah, this works");
-
- "Blah blah, this works" needs 22 characters. You've only allocated 18.
-
- 22-18= 4 characters illegally written to memory. If your code runs past this
- point...
-
- ; for (i=0; i<=15; i++)
- ; {
- ; strcpy(a[i],s);
-
- sizeof a[i] = 20, so:
-
- 22-20 = 2 characters written to a[i+1] which on the last iteration will write
- 2 characters beyond the end of *a* (illegally).
-
-
- ; }
- ; for (i=0; i<=15; i++)
- ; {
- ; printf("%s\n",a[i]);
- ; }
- ; free(s);
- ; return 0;
- ;}
- ;
- ;--------------------------------
- ;
- ;This is the same situation but it works fine here ?!
- ;
- In my vernacular, *works* does not correctly describe this code.
-
- Bill
-
- "Whatcha got on?...Your mind?"
-